﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace WinFormClient
{
    //暂时可以不用这个详细结果信息，直接函数int返回就可以，0=成功 -1=失败
    public enum RESULTINFO
    {
        SUCCESS = 0,
        NETERROR = -1,
        EMPTY = -2
    };

    public class ClientDataCenter : WinFormClient.IDataHandler
    {
        public ClientData data;

        //里面的代码用于从本地文件读取 data 对象;
        public ClientDataCenter()
        {
            if (data == null)
            {
                Stream stream = new FileStream("LocalStorage.dat", FileMode.OpenOrCreate,
                    FileAccess.Read, FileShare.None);
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    data = (ClientData)formatter.Deserialize(stream);
                }
                catch (Exception ex)
                {
                    data = new ClientData();
                }
                finally { stream.Close(); }
            }
        }

        public int TryGetGroups(out GroupSet groups, out RESULTINFO result)
        {
            throw new System.NotImplementedException();
        }

        public int TryGetTopics(out TopicSet topics, out RESULTINFO result)
        {
            throw new System.NotImplementedException();
        }

        public int TryGetMessages(out MessageSet msgs, out RESULTINFO result)
        {
            throw new System.NotImplementedException();
        }

        public int TryAddMesseage(Message msg, out RESULTINFO result)
        {
            throw new System.NotImplementedException();
        }

        public int TryAddTopic(Topic topic, out RESULTINFO result)
        {
            throw new System.NotImplementedException();
        }

        //用于本地保存 在client.Exit()里面已经调用
        public void LocalSave()
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("LocalStorage.dat", FileMode.Create,
                FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, data);
                stream.Close();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }            
        }
        
    }
}
